package com.example.tongyao.system.config;

import com.example.tongyao.utils.DataResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 业务系统 前端控制器
 * </p>
 *
 * @author tongyao
 * @since 2021-08-15
 */
@Api(tags = "TongYao框架默认业务系统控制器")
@RestController
public class SysCoreController {

    @ApiOperation(
            value = "默认无登录提示",
            notes = "当前没有获得登录的信息，自动调用此接口。",
            httpMethod = "GET")
    @GetMapping(value = "/defaultMsg" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public void defaultMsg(HttpServletRequest request, HttpServletResponse response){
        throw new AccessDeniedException("您的登录授权已过期，请重新登录！");
    }

    //后期改成名字 ()
    //如果可以是用RbacServiceImpl，下面那个注解可以不用
    //@PreAuthorize("hasRole('ROLE_RO222LE')")
    @ApiOperation(
            value = "获得用户信息",
            notes = "获得用户当前登录的用户信息",
            httpMethod = "GET")
    @GetMapping(value = "/getUser" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult getUser(){
        return DataResult.setResult(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
    }

    /**
     * 自定义退出登录
     * @return
     */
    @ApiOperation(
            value = "登出",
            notes = "安全退出登录",
            httpMethod = "GET")
    @GetMapping(value = "/logoutInfo" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public DataResult logoutInfo(){
        //删除redis缓存
        return DataResult.setSuccess("登录退出成功！");
    }

    /**
     * 没有权限 抛出401异常，全局统一处理
     * @throws Exception
     */
    @ApiOperation(
            value = "无权限",
            notes = "访问接口等菜单无权限会默认调用此接口。",
            httpMethod = "GET")
    @GetMapping(value = "/unauthorized" , produces = {MediaType.APPLICATION_JSON_VALUE})
    public void unauthorized(){
        throw new AccessDeniedException("您没有权限访问！");
    }
}
